<?php
class User{
	function User(){
		if(!isset($_SESSION[MEMCACHE_ID.'user_deal_id'])){
			$_SESSION[MEMCACHE_ID.'user_deal_id']=0;
		}
		if($_SESSION[MEMCACHE_ID.'user_deal_id']){
			$user	=	self::getUser((int)$_SESSION[MEMCACHE_ID.'user_deal_id']);
			if($user){
				$_SESSION['userDeal']=$user;
			}
			else{
				self::LogOut();
			}
		}
	}

	static function getUser($user_id=0,$update_cache=false,$delcache=false){
		$user=array();
		if($user_id){
			if(is_string($user_id) && intval($user_id) > 0){
				$user_id = intval($user_id);
			}
			$condition = is_string($user_id) ? "username='$user_id'" : "id=$user_id";
			if($delcache){//Xoá cache
				CacheLib::delete("user:$user_id",'userDeal');
				return true;
			}
			else{
				if(!$update_cache){
					$user = CacheLib::get("user:$user_id",0,'userDeal');
				}
				if(!$user){
					$sql 	= "SELECT * FROM ".T_USER_DEAL." WHERE $condition AND status = 1 AND type = 0 LIMIT 0,1";
					$user 	= mysql_fetch_assoc(DB::query($sql));
					
					if($user['item_id'] != 0){
						$user['item_id'] = unserialize($user['item_id']);
					}
					CacheLib::set("user:$user_id",$user,0,'userDeal');
				}
			}
			
		}
		return $user;
	}

	static function LogIn($user_or_id = 0){
		if(is_array($user_or_id) && isset($user_or_id['id']))
			$user_id=(int)$user_or_id['id'];

		$user_id = (isset($user_id)) ? $user_id : $user_or_id ;

		$_SESSION[MEMCACHE_ID.'user_deal_id'] = $user_id;

		if($user_id){
			DB::query("UPDATE ".T_USER_DEAL." SET last_login = ".TIME_NOW.",last_ip='".FunctionLib::ip()."' WHERE id=".$user_id);
			$user=self::getUser($user_id,true);
			if($user){
				$_SESSION['userDeal']=$user;
			}
		}
	}

	static function LogOut(){
		if(isset($_SESSION[MEMCACHE_ID.'user_deal_id'])){
			DB::query("UPDATE ".T_USER_DEAL." SET last_login = ".TIME_NOW.", last_ip='".FunctionLib::ip()."' WHERE id=".(int)$_SESSION[MEMCACHE_ID.'user_deal_id'],__LINE__.__FILE__);
		}
		
		$_SESSION[MEMCACHE_ID.'user_deal_id'] = 0;
		if(isset($_SESSION['userDeal'])){
			unset($_SESSION['userDeal']);
		}
	}

	static function is_login(){
		return (isset($_SESSION[MEMCACHE_ID.'user_deal_id']) && $_SESSION[MEMCACHE_ID.'user_deal_id']!=0);
	}
	static function id(){
		return isset($_SESSION[MEMCACHE_ID.'user_deal_id'])?(int)$_SESSION[MEMCACHE_ID.'user_deal_id']:0;
	}
	static function username(){
		if(isset($_SESSION[MEMCACHE_ID.'user_deal_id'])){
			if(isset($_SESSION['userDeal']['username'])&&$_SESSION['userDeal']['username']){
				return $_SESSION['userDeal']['username'];
			}
		}
		return '';
	}
	static function encode_password($password){
		return md5($password.'-ShopTeam2010');
	}
	
}
?>